package AipBase

import (
	"baidu/client"
	"baidu/params"
	"encoding/json"
	"io/ioutil"
	"reflect"
	"strings"
	"time"
	"xiaoYuShop/go/front/tool/md5"
)

func Auth(refresh bool, AccessTokenUrl string, paramsR map[string]interface{}) map[string]interface{} {
	if !refresh {
		var readAuthObjRes map[string]interface{} = readAuthObj()
		if readAuthObjRes != nil {
			return readAuthObj()
		}
	}

	var authObj map[string]interface{} = client.Get(AccessTokenUrl, paramsR, nil)

	params.IsCloudUser = !IsPermission(authObj)

	// 缓存认证过了的信息
	WriteAuthObj(authObj)

	return authObj
}

/**
 * 读取本地缓存
 * @return array
 */
func readAuthObj() map[string]interface{} {
	var fileName string = getAuthFilePath()
	b, err := ioutil.ReadFile(fileName)
	if err != nil {
		return nil
	}
	var obj map[string]interface{}
	err = json.Unmarshal(b, &obj)
	if err != nil {
		panic(err)
	}

	params.IsCloudUser = reflect.ValueOf(obj["is_cloud_user"]).Bool()
	obj["is_read"] = true

	var lastTime float64 = reflect.ValueOf(obj["time"]).Float()
	var expiresIn float64 = reflect.ValueOf(obj["expires_in"]).Float()

	if params.IsCloudUser == true || lastTime+expiresIn-30 > float64(time.Now().Unix()) {
		return obj
	}

	return nil
}

func getAuthFilePath() string {
	return "./" + md5.ToMd5(params.ApiKey)
}

/**
 * 判断认证是否有权限
 * @param  array   $authObj
 * @return boolean
 */
func IsPermission(autoObj map[string]interface{}) bool {
	if autoObj["scope"] == "" {
		return false
	}

	var scope string = reflect.ValueOf(autoObj["scope"]).String()
	var scopeArr []string = strings.Fields(scope)

	for _, item := range scopeArr {
		if item == params.Scope {
			return true
		}
	}

	return false
}

/**
 * 写入本地文件
 * @param  array $obj
 * @return void
 */
func WriteAuthObj(obj map[string]interface{}) {
	if obj["is_read"] == true {
		return
	}
	obj["time"] = int(time.Now().Unix())
	obj["is_cloud_user"] = params.IsCloudUser

	b, _ := json.Marshal(obj)
	var authFilePath string = getAuthFilePath()
	err := ioutil.WriteFile(authFilePath, b, 0666)
	if err != nil {
		panic(err)
	}
}
